package com.crossdomain.www.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.crossdomain.common.ControllerResponseBody;
import com.crossdomain.common.GlobalResultCode;
import com.crossdomain.www.controller.domain.User;



public class UserLoginFilter implements Filter{
    Logger logger = LoggerFactory.getLogger(UserLoginFilter.class);
    
    protected static String[] excludeUrls = new String[]{"/user/findUserMessageNoLogin.action","/user/mockLogin.action"};
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
            throw new ServletException("OncePerRequestFilter just supports HTTP requests");
        }
        
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        
        HttpSession session = httpRequest.getSession(true);
        StringBuffer url = httpRequest.getRequestURL();
        
        if (excludeUrls != null && excludeUrls.length > 0) {
            for (String str : excludeUrls) {
                if (str.equals(url.toString())||url.indexOf(str) >= 0) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }

            Object object = session.getAttribute("user");
            User userInfo = object == null ? null : (User) object;
            if (userInfo == null) {
                //yuzhao增加了j参数，为了解决app给html5传参数
                boolean isAjaxRequest = isAjaxRequest(httpRequest);
                if(isAjaxRequest) {
                    //老版本的app使用ajax的头发送数据,老版本遗留问题，删除相关代码 by jannal
                    httpResponse.setCharacterEncoding("UTF-8");
                    ControllerResponseBody<Object> ControllerResponseBody = new ControllerResponseBody<Object>();
                    ControllerResponseBody.setStatus(ControllerResponseBody.FAILED);
                    ControllerResponseBody.setCode(GlobalResultCode.CommonResultCode.NEED_LOGIN);
                    ControllerResponseBody.setMsg("请重新登录！");
                    String json = JSON.toJSONString(ControllerResponseBody);
                    httpResponse.getOutputStream().write(json.getBytes("UTF-8"));
                }else{
                    httpResponse.sendRedirect(httpRequest.getContextPath()+"/static/index/index.html"); 
                }
                return;
            }
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        return requestType != null && requestType.equals("XMLHttpRequest");
   }

}
